package mspbots.liongard.client.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import mspbots.liongard.common.RabbitKeys;
import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * com.mspbots.sync.config.RabbitConfigurer
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/7/29
 */
@Configuration
public class RabbitConfiguration {

    private final AmqpAdmin amqpAdmin;
    private final Exchange exchange;
    Map<String, Object> args = new HashMap<>(4) {{
        put("x-dead-letter-exchange", RabbitKeys.BASE_EXCHANGE_NAME);
        put("x-dead-letter-routing-key", RabbitKeys.BAD_MESSAGE_QUEUE_KEY);
    }};

    public RabbitConfiguration(AmqpAdmin amqpAdmin) {
        this.amqpAdmin = amqpAdmin;
        this.exchange = ExchangeBuilder.directExchange(RabbitKeys.BASE_EXCHANGE_NAME).build();
        this.amqpAdmin.declareExchange(exchange);
    }

    @Bean
    public void declareTaskQueue() {

        Queue queue = QueueBuilder.durable("liongard.bad.message").withArgument("x-message-ttl", 1000 * 60 * 60 * 24).build();
        this.amqpAdmin.declareQueue(queue);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(queue)
                .to(exchange).with(RabbitKeys.BAD_MESSAGE_QUEUE_KEY).noargs());

        queue = QueueBuilder.durable("liongard.logs.task.sync").withArguments(args).build();
        this.amqpAdmin.declareQueue(queue);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(queue)
                .to(exchange).with(RabbitKeys.LOGS_TASK_QUEUE_KEY).noargs());

        queue = QueueBuilder.durable("liongard.distributed.task.sync").withArguments(args).build();
        this.amqpAdmin.declareQueue(queue);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(queue)
                .to(exchange).with(RabbitKeys.DISTRIBUTED_TASK_QUEUE_KEY).noargs());

    }

    @Bean
    public void declareQueue() {


    }

    @Bean
    public MessageConverter rabbitMessageConverter(ObjectMapper objectMapper) {
        return new Jackson2JsonMessageConverter(objectMapper);
    }
}
